package com.hcb.logsdk.manager;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.hcb.logsdk.okhttp.listener.DisposeDataListener;
import com.hcb.logsdk.okhttp.request.RequestCenter;
import com.hcb.logsdk.service.PushLogService;
import com.hcb.logsdk.socketio.listener.IConstants;
import com.hcb.logsdk.socketio.socket.AppSocket;
import com.hcb.logsdk.util.C;
import com.hcb.logsdk.util.L;
import com.hcb.logsdk.util.Utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author WangGuoWei
 * @time 2018/1/4 15:18
 * @des ${TODO}
 * <p>
 * ┽
 * ┽                            _ooOoo_
 * ┽                           o8888888o
 * ┽                           88" . "88
 * ┽                           (| -_- |)
 * ┽                           O\  =  /O
 * ┽                        ____/`---'\____
 * ┽                      .'  \\|     |//  `.
 * ┽                     /  \\|||  :  |||//  \
 * ┽                    /  _||||| -:- |||||-  \
 * ┽                    |   | \\\  -  /// |   |
 * ┽                    | \_|  ''\---/''  |   |
 * ┽                    \  .-\__  `-`  ___/-. /
 * ┽                  ___`. .'  /--.--\  `. . __
 * ┽               ."" '<  `.___\_<|>_/___.'  >'"".
 * ┽              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 * ┽              \  \ `-.   \_ __\ /__ _/   .-` /  /
 * ┽         ======`-.____`-.___\_____/___.-`____.-'======
 * ┽                            `=---='
 * ┽         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 * ┽                      佛祖保佑       永无BUG
 * ┽
 * ┽
 * ┽
 * @updateAuthor $Author$
 * @updateDate $Date$
 * @updateDes ${TODO}
 */
public class LOGSDKManager {
    private Context ctx;
    private static LOGSDKManager INSTANCE;
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
    private ScheduledExecutorService uploadLogScheduler = Executors.newScheduledThreadPool(5);
    private ScheduledExecutorService checkSocketConnectScheduler = Executors.newScheduledThreadPool(5);


    public static void setApiUrl(String apiUrl) {
        API_URL = apiUrl;
    }

    public static String API_URL = "http://192.168.1.3:9999";//线上


    /**
     * 提供系统调用的构造函数，
     */
    private LOGSDKManager() {
        INSTANCE = this;
    }

    /**
     * 获得实例
     *
     * @return
     */
    public static LOGSDKManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new LOGSDKManager();
        }
        return INSTANCE;
    }


    public ScheduledExecutorService getScheduler() {
        if(scheduler.isTerminated())
            scheduler =  Executors.newScheduledThreadPool(5);
        return scheduler;
    }
    public ScheduledExecutorService getUploadLogScheduler() {
        if(uploadLogScheduler.isTerminated())
            uploadLogScheduler =  Executors.newScheduledThreadPool(5);
        return uploadLogScheduler;
    }
    public ScheduledExecutorService getCheckSocketConnectScheduler() {
        if(checkSocketConnectScheduler.isTerminated())
            checkSocketConnectScheduler =  Executors.newScheduledThreadPool(5);
        return checkSocketConnectScheduler;
    }



    public void startSendLog(String deviceNo){

        RequestCenter.startSendLog(deviceNo,new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                Utils.showToastCenter(ctx,"发送成功");
            }

            @Override
            public void onFailure(Object reasonObj) {
                Utils.showToastCenter(ctx,"发送失败");
            }
        });

    }



    public void endSendLog(String deviceNo){

        RequestCenter.endSendLog(deviceNo,new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                Utils.showToastCenter(ctx,"结束成功");
            }

            @Override
            public void onFailure(Object reasonObj) {
                Utils.showToastCenter(ctx,"结束失败");
            }
        });

    }




    public Context getCtx() {
        return ctx;
    }

    public void initImServices(Context cx) {
        this.ctx = cx;
        Intent intent = new Intent(cx, PushLogService.class);
        cx.bindService(intent, conn, cx.BIND_AUTO_CREATE);
    }
    public void startServices() {
        Intent intent = new Intent(ctx, PushLogService.class);
        ctx.bindService(intent, conn, ctx.BIND_AUTO_CREATE);
    }


    private PushLogService mPushService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("PushLogService", "service conn onServiceDisconnected " + name);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("PushLogService", "service 开启成功！！！ ");
            C.SOCKET_CONNECT_COUNT = 0;

            mPushService = ((PushLogService.LocalBinder) service).getService();
            if (mPushService != null) {
                mPushService.mPushConn.setSocketPushDataListener();
                mPushService.mPushConn.setSDKManager(LOGSDKManager.this);
                startconnect();
            }
        }
    };


    public void init(Context ctx) {
        initImServices(ctx);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(IConstants.SERVICE_STOP);
        ctx.registerReceiver(mReceiver, mFilter);
    }
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(IConstants.SERVICE_STOP)) {
                Log.i("PushLogService", "收到重启广播  service重启... ");
                startServices();
                C.SOCKET_CONNECT_COUNT = 0;
            }
        }
    };

    public void sendLog(String event,String msg){

        if(AppSocket.getInstance() != null)
            AppSocket.getInstance().sendLog2Server(event,msg);

    }
    public boolean LogSocketConnect(){

        return L.isConnected;

    }




    public void startconnect(){
        mPushService.push_connect(2);
        Log.i("PushLogService","Log----   连接Log服务器: "+API_URL);
    }

    public void stopconnect(){
        mPushService.close_connect();
    }

    public void destroy(){
        ctx.unbindService(conn);
        Log.i("PushLogService", "销毁OR重启  C.SOCKET_RECONNECT...  "+C.SOCKET_RECONNECT);
        if(!C.SOCKET_RECONNECT){
            ctx.unregisterReceiver(mReceiver);
            C.SOCKET_RECONNECT = false;
        }

    }

}
